﻿@using ST.Torch.WebApi.Web.Core;
@inherits UtilRazorPage<object>
@{
    //Layout = "~/Views/Shared/_TableListLayout.cshtml";
    Layout = "~/Views/Shared/__ComponentLayout.cshtml";
    string randomId = Guid.NewGuid().ToString();
}


    <div style="padding: 5px;">
        <div class="layui-card">
            <div class="layui-card-body">
                <table class="layui-hide" id="tableEle_@randomId" lay-filter="tableEle_@randomId"></table>
            </div>
        </div>
    </div>
@section footer
{
    <script type="text/html" id="toolbarDemo_@randomId">
         <div style="display:flex">
             <div style="flex:1">
                  <div class="layui-btn-container">
                      <button class="layui-btn layui-btn-sm" lay-event="AddData" lay-permission="AddMenuPage"><i class="layui-icon layui-icon-add-circle"></i>@L("新增")</button>
                      <button class="layui-btn layui-btn-sm" lay-event="DelData" lay-permission="DelMenuPage"><i class="layui-icon layui-icon-delete"></i>@L("删除")</button>
                     <!-- <button class="layui-btn layui-btn-sm" id="reloadTest">
                        重载测试
                        <i class="layui-icon layui-icon-down layui-font-12"></i>
                      </button> -->
                </div>
             </div>
            <div style="width:200px;display:none">
                 <input type="text"  id="Querykey_@randomId" placeholder="" style="display: inline-block;height: 30px; line-height: 30px;margin-right:5px" class="layui-input">
                 <button class="layui-btn layui-btn-sm" lay-event="Querykey_@randomId">@L("查询")</button>
            </div>

        </div>
    </script>
    <script type="text/html" id="barDemo_@randomId">
        <div class="layui-clear-space">
          <button class="layui-btn layui-btn-xs" lay-event="edit" lay-permission="EditMenuPage">@L("编辑")</button>
          <a class="layui-btn layui-btn-xs" lay-event="more">
                @L("更多")
            <i class="layui-icon layui-icon-down"></i>
          </a>
        </div>
    </script>
    <script type="text/html" id="IsHideTpl_@randomId">
        <!-- 这里的 checked 的状态只是演示 -->
        <input type="checkbox" name="IsHide" value="{{d.Id}}" lay-skin="switch" lay-text="隐藏|" lay-filter="IsStateF" {{ d.IsHide == 1 ? "checked" : "" }}>
    </script>
    <script type="text/html" id="IconTpl_@randomId">
      
         <i class="{{d.Icon}}"></i>
    </script>
    <script>


        layui.use(['table', 'toast', 'dropdown', 'jquery', 'form', 'treetable'], function () {
            var table = layui.table;
            var dropdown = layui.dropdown;
            var form = layui.form;
            var treetable = layui.treetable;

            var toast = layui.toast;
            var $ = layui.jquery;
            var treetableRender = function () {
            // 创建渲染实例
            treetable.render({
                treeColIndex: 1,
                treeSpid: '00000000-0000-0000-0000-000000000000',
                treeIdName: 'Id',
                treePidName: 'ParentId',
                skin: 'line',
                elem: '#tableEle_@randomId',
                url: '/api/SYSMenu/GetAllSystemMenu', // 此处为静态模拟数据，实际使用时需换成真实接口
                method: 'post',//如果无需自定义HTTP类型，可不加该参数
                    toolbar: '#toolbarDemo_@randomId',
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                height: 'full-95', // 最大高度减去其他容器已占有的高度差
                //limit: 20,//注意：请务必确保 limit 参数（默认：10）是与你服务端限定的数据条数一致
                css: [ // 重设当前表格样式
                    '.layui-table-tool-temp{padding-right: 145px;}'
                ].join(''),
                cellMinWidth: 80,
                //totalRow: true, // 开启合计行
                //page: true,
                cols: [[
                        { type: 'checkbox' },//, fixed: 'left'
                        { field: 'Title', title: '@L("名称")' },
                        { field: 'Href', title: '@L("路径")' },
                        { field: 'PermissionId', title: '@L("权限标识")' },

                        { field: 'Icon', title: '@L("图标")', width: 30, templet: '#IconTpl_@randomId' },
                    { field: 'Icon', title: ' @L("图标CSS") <i class="layui-icon layui-icon-tips layui-font-14" lay-event="email-tips" title="该字段开启了编辑功能" style="margin-left: 5px;"></i>', fieldTitle: '邮箱', hide: 0, edit: 'text' },
                    { field: 'OpenType', width: 180, title: '@L("打开方式")' },
                        { field: 'TypeStr', width: 120, title: '@L("类型")' },
                        { field: 'Sort', width: 20, title: '@L("排序")' },
                        { field: 'IsHide', width: 120, title: '@L("是否隐藏")', templet: '#IsHideTpl_@randomId' },
                        { fixed: 'right', title: '@L("操作")', width: 134, minWidth: 125, toolbar: '#barDemo_@randomId' }
                ]],
                /*
                parseData: function (res) {
                    console.log(res)
                    return {
                        "count": res.Data.TotalCount,
                        'statusCode': res.StatusCode,
                        'data': res.Data.Items
                    };
                },
                response: {
                    statusName: 'statusCode',
                    statusCode: 200
                },
                */
                done: function () {

                    permissionUI();
                },
                error: function (res, msg) {
                    console.log(res, msg)
                }
            });
            }
     
            treetableRender();
            // 工具栏事件
            table.on('toolbar(tableEle_@randomId)', function (obj) {
                var id = obj.config.id;
                var checkStatus = table.checkStatus(id);
                var othis = lay(this);
                switch (obj.event) {
                    case 'Querykey_@randomId':
                        var key = $("#Querykey_@randomId").val();
                        table.reloadData('tableEle_@randomId', {
                            where: {
                                key: key,
                                //test: '新的 test2',
                                //token: '新的 token2'
                            },
                            //scrollPos: 'fixed',  // 保持滚动条位置不变 - v2.7.3 新增
                            //height: 2000, // 测试无效参数（即与数据无关的参数设置无效，此处以 height 设置无效为例）
                            //url: '404',
                            page: { curr: 1, limit: 30 } // 重新指向分页
                        });
                        break;
                    case 'AddData':
                        var buttonEle = button.load({ elem: this });
                        var msgTitle = '@L("新增数据")';
                        GetViewHtml('/SYS/Menu/RenderViewToString', 'AddOrEdit', [], function (html) {
                            layer.open({
                                title: msgTitle,
                                type: 1,
                                area: ['40%', '80%'],
                                content: html,
                                success: function (layero, index, that) {
                                    G_LayuiOpenTypeIndex = index;
                                },
                                end: function (index, layero) {
                                    // 这里写关闭窗口后需要执行的代码
                                    console.log('窗口被关闭了End');
                                    reloadTableData();
                                },
                            });
                            buttonEle.stop();

                        })
                        break;
                    case 'DelData':

                        var data = checkStatus.data;

                        //obj.del(); // 删除对应行（tr）的DOM结构
                        console.log(data)
                        if (data.length >= 1) {
                            var msgTitle = '@L("确定删除选中的数据吗?")'
                            layer.confirm(msgTitle, function (index) {
                                var Ids = [];
                                for (var i in data) {
                                    Ids.push(data[i].Id)
                                }
                                DelBatchData(Ids)
                                layer.close(index);

                            });

                        } else {
                            var msgTitle = '@L("请选择要删除的数据")'

                            layer.alert(msgTitle);
                        }
                        //layer.alert(layui.util.escape(JSON.stringify(data)));

                        break;
                    case 'LAYTABLE_TIPS':
                        layer.alert('自定义工具栏图标按钮');
                        break;
                };
            });
            // 表头自定义元素工具事件 --- 2.8.8+
            table.on('colTool(tableEle_@randomId)', function (obj) {
                var event = obj.event;
                console.log(obj);
                if (event === 'email-tips') {
                    // layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
                    //     title: '当前列属性配置项'
                    // });
                    var href = "https://layui.dev/docs/2/icon/#examples";
                    window.open(href, '_blank');
                }
            });

            // 触发单元格工具事件
            table.on('tool(tableEle_@randomId)', function (obj) { // 双击 toolDouble
                var data = obj.data; // 获得当前行数据
                // console.log(obj)
                if (obj.event === 'edit') {
                    var buttonEle = button.load({ elem: this });
                    var msgTitle = '@L("编辑")【' + data.Title + '】'
                    GetViewHtml('/SYS/Menu/RenderViewToString', 'AddOrEdit', [data.Id], function (html) {
                        layer.open({
                            title: msgTitle,
                            type: 1,
                            area: ['40%', '80%'],
                            content: html,
                            success: function (layero, index, that) {
                                G_LayuiOpenTypeIndex = index;
                            },
                            end: function (index, layero) {
                                // 这里写关闭窗口后需要执行的代码
                                console.log('窗口被关闭了End');
                                reloadTableData();
                            },
                        });
                        buttonEle.stop();

                    })

                } else if (obj.event === 'more') {
                     var dataDrop=[];
                    dataDrop.push({
                            title: '@L("查看")',
                            id: 'detail'
                        })
                    if(IsPermission('DelMenuPage')){
                        dataDrop.push( {
                            title: '@L("删除")',
                            id: 'del'
                        })
                    }
                    // 更多 - 下拉菜单
                    dropdown.render({
                        elem: this, // 触发事件的 DOM 对象
                        show: true, // 外部事件触发即显示
                        // data: [{
                        //     title: '@L("查看")',
                        //     id: 'detail'
                        // }, {
                        //     title: '删除',
                        //     id: 'del'
                        // }],
                        data:dataDrop,
                        click: function (menudata) {
                            if (menudata.id === 'detail') {
                                //layer.msg('查看操作，当前行 ID:' + data.id);
                                var msg = '@L("当前列数据")'
                                layer.alert(layui.util.escape(JSON.stringify(data)), {
                                    title: msg
                                });
                            } else if (menudata.id === 'del') {
                                var msg = '@L("确认删除行")';
                                layer.confirm(msg+' [' + data.Title + '] ?', function (index) {
                                    //obj.del(); // 删除对应行（tr）的DOM结构
                                    DelData(data.Id,true);
                                    //var msgTitle = '@L("删除成功")'
                                    //Toast(msgTitle)
                                    layer.close(index);
                                    // 向服务端发送删除指令
                                });
                            }
                        },
                        align: 'right', // 右对齐弹出
                        style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                    })
                }
            });

            // 触发表格复选框选择
            table.on('checkbox(tableEle_@randomId)', function (obj) {
                console.log(obj)
            });

            // 触发表格单选框选择
            table.on('radio(tableEle_@randomId)', function (obj) {
                console.log(obj)
            });

            // 行单击事件
            table.on('row(tableEle_@randomId)', function (obj) {
                //console.log(obj);
                //layer.closeAll('tips');
            });
            // 行双击事件
            table.on('rowDouble(tableEle_@randomId)', function (obj) {
                console.log(obj);
            });

            // 状态 - 开关操作
            form.on('switch(IsStateF)', function (obj) {
                console.log(obj)
                var id = this.value;
                var name = this.name;
                UpdateIsHide(id, obj.elem.checked)
                //layer.tips(id + ' ' + name + ': ' + obj.elem.checked, obj.othis);
            });
            function Toasttt(msg, type = "success") {
                if (type == "success") {
                    toast.success({
                        message: msg,
                    });
                }
            }
            // 单元格编辑事件
            table.on('edit(tableEle_@randomId)', function (obj) {
                var field = obj.field; // 得到字段
                var value = obj.value; // 得到修改后的值
                var data = obj.data; // 得到所在行所有键值
                // 值的校验
                if (field === 'email') {
                    if (!/^([a-zA-Z0-9_\.\-])+\@@(([a - zA - Z0 - 9\-]) +\.)+([a-zA-Z0-9]{2,4})+$/.test(obj.value)) {
                        layer.tips('输入的邮箱格式不正确，请重新编辑', this, { tips: 1 });
                        return obj.reedit(); // 重新编辑 -- v2.8.0 新增
                    }
                }
                if (field == "Icon") {
                    // 编辑后续操作，如提交更新请求，以完成真实的数据更新
                    //layer.msg('编辑成功', { icon: 1 });
                    console.log(data)
                    // 其他更新操作
                    var update = {};
                    if (value.indexOf("layui-icon ") == -1) {
                        value = "layui-icon " + value
                    }
                    update[field] = value;
                    
                    obj.update(update);
                    Update(obj.data)
                }
               
            });


            function DelData(Id, IsToast = false) {
                var formData = {
                    Id: Id
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/SYSMenu/Delete',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                            toast.success({
                                message: '@L("删除成功")',
                            });
                            reloadTableData();
                        } else {
                            toast.error({
                                message: '@L("删除失败")',
                            });

                        }
                    }
                });
            }
            function DelBatchData(Ids) {
                var formData = {
                    Ids: Ids
                };
                $.ajax({
                    type: 'POST',
                    url: '/api/SYSMenu/DeleteBatch',//发送请求
                    data: formData,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                            toast.success({
                                message: '@L("删除成功")',
                            });
                            reloadTableData();
                        } else {
                            toast.error({
                                message: '@L("删除失败")',
                            });
                        }
                    }
                });
            }

            function Update(data) {
                $.ajax({
                    type: 'POST',
                    url: '/api/SYSMenu/Update',//发送请求
                    data: data,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                            toast.success({
                                message: '@L("删除成功")',
                            });
                            reloadTableData();

                        } else {

                            toast.error({
                                message: '@L("修改失败")',
                            });

                        }
                    }
                });

            }
            function UpdateIsHide(Id, State) {
                var data = {
                    Id: Id,
                    State: State
                }
                $.ajax({
                    type: 'POST',
                    url: '/api/SYSMenu/UpdateIsHide',//发送请求
                    data: data,
                    success: function (result) {
                        console.log(result)
                        if (result.Succeeded) {
                            toast.success({
                                message: '@L("修改成功")',
                            });
                            //charset('@L("修改成功")')

                        } else {

                            toast.error({
                                message: '@L("修改失败")',
                            });

                        }
                    }
                });

            }

            function reloadTableData() {
                var key = $("#Querykey_@randomId").val();
                treetableRender();
                // treetable.reloadData('tableEle_@randomId', {
                //     where: {
                //         key: key,
                //     },
                // });
            }


        });

       
    </script>

}

